<script lang="ts" setup>
import type { DataType } from './types';
import { ref, computed, onMounted,watch } from 'vue';
import type { VxeGridProps } from '#/adapter/vxe-table';

import { Page } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { Button, Image, message, Popconfirm, Space } from 'ant-design-vue';
import Upload from "#/components/Upload";
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteAsset, getAssets,toWebp } from '#/api/system';
import Icon from '#/components/Icons';
import { formatImagesList } from '#/utils';

defineOptions({
  name: 'UserAdminAssetIndex',
});

const router = useRouter();
const routeMeta = router.currentRoute.value.meta;
const viewTitle = routeMeta.title.replace('管理', '');
const image = ref('');
function isImageFile(filename: string) {
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp','.webp']; // 图片格式的后缀列表

  const fileExtension = filename
    .slice(Math.max(0, filename.lastIndexOf('.')))
    .toLowerCase(); // 提取文件的后缀并转换为小写

  return imageExtensions.includes(fileExtension); // 检查提取到的后缀是否在图片格式的后缀列表中
}
const gridOptions: VxeGridProps<DataType> = {
  rowConfig: {
    isHover: true,
  },
  checkboxConfig: {
    labelField: 'name',
    highlight: true,
    range: true,
  },
  columns: [
    { title: $t('page.common.Code'), type: 'seq', width: 50, showOverflow: true },
    { field: 'user', title: $t('admin.UserName'), slots: { default: 'user' } },
    { field: 'file_size', title: $t('admin.fileSize')},
    { field: 'filename', title: $t('admin.fileName') },
    { field: 'preview', title: $t('admin.preview'), slots: { default: 'preview' } },
    { field: 'file_path', title: $t('admin.filePath') },
    {
      slots: { default: 'action' },
      field: 'action',
      fixed: 'right',
      title: $t('page.common.Action'),
      width: 240,
    },
  ],
  height: '800px',
  keepSource: true,
  pagerConfig: {
    layouts: ['Total', 'Sizes', 'PrevPage', 'Number', 'NextPage', 'FullJump'], // 带总条数和每页大小选择
    pageSize: 20,
    pageSizes: [10, 20, 50, 100],
  },




  proxyConfig: {
      props: {
        result: 'list',   // 这是你的数据列表字段
        total: 'total',   // 这是总条数字段，分页组件需要它
      },
      ajax: {
        query: async ({ page }) => {
          const { data } = await getAssets({
            page: page.currentPage,
            limit: page.pageSize,
          });

          data.list = formatImagesList(data.list, 'file_path');
        

          // 确保返回 list 和 total
          return {
            list: data.list,
            total: data.total,
          };
        },
      },
  },

  toolbarConfig: {
    custom: true,
    // export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};

const [Grid, GridApi] = useVbenVxeGrid({
  gridOptions,
});

/**
 * 删除操作
 */
const handleDelete = async (row?: DataType) => {
  const $table = GridApi.grid;
  if ($table && row?.id) {
    const { msg } = await deleteAsset(row);
    $table.remove(row);
    message.success(msg);
  }
};

const openDialog = async(row?:DataType)=>{
  const { msg } =await toWebp({id:row.id});
  if(msg == 'success'){
    message.success(msg);
    GridApi.reload();
}
}

watch(
  image,
  (newVal,oldUrl) => {
  GridApi.reload(); // 重新加载表格
  },
  { immediate: true }
);
</script>




<template>
  <Page auto-content-height>
   
    <Grid :table-title="`${viewTitle} `+$t('page.common.List')">
         <template #toolbar-tools>
        <Upload name="file" class="filese" @change="handleChange"  :multiple="true" v-model="image" :list-type="false" :show-upload-list="false"></Upload>
      </template>
      <template #preview="{ row }">
        <Image
          v-if="row.file_path && isImageFile(row.file_path)"
          :src="row.file_path"
          :height="20"
          :width="60"
          style="object-fit: contain;" 
        />
        <span v-else> <Icon icon="ri:file-line" /></span>
      </template>
      <template #user="{ row }"> 用户名:{{ row.user?.user_login }} </template>

      <template #action="{ row }">
        <Space>
           <Button
            v-if="row.suffix!='webp' && 0"
            type="primary"
            @click="openDialog(row)"
          >
            <template #icon>
              <span class="anticon">
                <Icon icon="ri:file-edit-line" />
              </span>
            </template>
            转为webp
          </Button>
          <Popconfirm
            :cancel-text="$t('page.common.No')"
            :ok-text="$t('page.common.Yes')"
            :title="$t('page.common.Confirm Delete')"
            @confirm="handleDelete(row)"
          >
            <Button danger type="primary">
              <template #icon>
                <span class="anticon">
                  <Icon icon="ri:delete-bin-line" />
                </span>
              </template>
              {{$t('page.common.Delete')}}
            </Button>
          </Popconfirm>
        </Space>
      </template>

    </Grid>


  </Page>
</template>
<style scoped>

 :deep(.ant-upload-list-item-container) {
     width: 50px !important;
      height: 50px !important;
  }

  :deep(.upload-init-me){
    width: 50px !important;
    height: 50px !important;
  }
  </style>